<?php

namespace yi\base;

use Exception;
use Yi;
use yi\di\ServiceLocator;

abstract class Application extends Module
{
    public $charset = 'UTF-8';

    public $controllerNamespace = 'app\controllers';

    /**
     * @var Controller the currently active controller instance
     */
    public $controller;

    public function __construct($config)
    {
        Yi::$app = $this;
        $this->preInit($config);
        //将config值赋值给对象熟悉 同时调用init方法
        //Yi::configure 会将
        Component::__construct($config);//
    }

    public function init()
    {
        $this->bootstrap();
    }

    protected function bootstrap()
    {

    }

    public function preInit(&$config)
    {
        if (isset($config['basePath'])) {
            $this->setBasePath($config['basePath']);
            unset($config['basePath']);
        } else {
            throw new Exception('The "basePath" configuration for the Application is required.');
        }

        // merge core components with custom components
        foreach ($this->coreComponents() as $id => $component) {
            if (!isset($config['components'][$id])) {
                $config['components'][$id] = $component;
            } elseif (is_array($config['components'][$id]) && !isset($config['components'][$id]['class'])) {
                $config['components'][$id]['class'] = $component['class'];
            }
        }
    }

    public function coreComponents()
    {
        return [
            'urlManager' => ['class' => 'yi\web\UrlManager'],
            'view' => ['class' => 'yii\web\View'],
        ];
    }


    public function run()
    {
        $response = $this->handleRequest($this->getRequest());
        $response->send();
    }

    /**
     * @return  Response $request
     */
    abstract public function handleRequest($request);

    public function setBasePath($path)
    {
        parent::setBasePath($path);
        Yi::setAlias('@app', $this->getBasePath());
    }


}
